package com.tiancheng.trade.authserver.utils;

import cn.dev33.satoken.jwt.SaJwtUtil;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.tiancheng.trade.commom.web.model.SubjectProfile;

import java.util.UUID;

/**
 * @Author: kellen
 * @Description:
 * @Date: create in 2024/11/13 11:11
 */
public class TokenGenerator {
    private final ObjectMapper objectMapper;
    private final String privateKey;

    public TokenGenerator(String privateKey) {
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.setVisibility(PropertyAccessor.SETTER, JsonAutoDetect.Visibility.NONE);
        objectMapper.setVisibility(PropertyAccessor.GETTER, JsonAutoDetect.Visibility.NONE);
        objectMapper.setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY);
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        this.objectMapper = objectMapper;
        this.privateKey = privateKey;
    }

    public String generate(long expiresIn, SubjectProfile profile) {
        String rand = UUID.randomUUID().toString().replace("-", "").substring(0, 16);
        String header = RSAUtils.encryptByPrivateKey(rand, this.privateKey);
        profile.getAttributes().put("expiration", System.currentTimeMillis() / 1000L + expiresIn);

        String payload;
        try {
            payload = this.objectMapper.writeValueAsString(profile);
        } catch (JsonProcessingException var8) {
            throw new RuntimeException(var8);
        }

        payload = AESUtils.encrypt(payload, rand);
        return header + "@" + payload;
    }
}
